package com.tengju.bff.interfaces.covercharge.job;

import com.alibaba.fastjson.JSONObject;
import com.tengju.bff.interfaces.covercharge.constant.CustTaskQueueCmdEnum;
import com.tengju.bff.interfaces.covercharge.constant.CustTaskQueueStatusEnum;
import com.tengju.bff.interfaces.covercharge.constant.HeavyKeyEnum;
import com.tengju.bff.interfaces.covercharge.entity.po.CustTaskQueue;
import com.tengju.bff.interfaces.covercharge.entity.vo.CashBackRes;
import com.tengju.bff.interfaces.covercharge.service.ICustTaskQueueService;
import com.tengju.bff.interfaces.covercharge.service.IServiceSelfCertificationWithdrawService;
import com.tengju.bff.interfaces.covercharge.util.alarmUtil.MsgSendUtil;
import com.tengju.bff.interfaces.covercharge.util.redis.HeavyUtil;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.ParseException;

/**
 * 自认证提现发起
 */
@Component
@Slf4j
public class AllWithdrawalJob {

    @Autowired
    private IServiceSelfCertificationWithdrawService withdrawService;

    @Autowired
    private ICustTaskQueueService iCustTaskQueueService;

    @XxlJob("allWithdrawalJob")
    public ReturnT<String> execute(String s) throws ParseException {
        if (HeavyUtil.isRun(HeavyKeyEnum.ALL_WITHDRAWAL_JOB_E.getCode())) {
            log.info("=batchWithdrawalJob=已经有正在运行的,跳过");
            return ReturnT.SUCCESS;
        } else {
            try {
                return this.exec();
            } catch (Exception e) {
                log.error("=batchWithdrawalJob=执行异常", e);
                return ReturnT.SUCCESS;
            } finally {
                HeavyUtil.runDone(HeavyKeyEnum.ALL_WITHDRAWAL_JOB_E.getCode());
            }
        }
    }

    private ReturnT<String> exec() {
        log.info("=batchWithdrawalJob_l=开始执行");
        Integer noRunCount = iCustTaskQueueService.notRunningOutOrder(CustTaskQueueCmdEnum.WITHDRAWAL.getCode());
        if (noRunCount == 0) {
            log.info("=batchWithdrawalJob_l=执行时没有需要批量提现的任务");
            return ReturnT.SUCCESS;
        }
        try {
            for (int j = 0; j < noRunCount; j++) {
                CustTaskQueue custTaskQueue = iCustTaskQueueService.getQueueIsNotRunning(CustTaskQueueCmdEnum.WITHDRAWAL.getCode());
                if (custTaskQueue == null) {
                    log.error("=batchWithdrawalJob_l=提现批量处理未按预期获取到提现数据;预期数量:{}", noRunCount);

                    return ReturnT.SUCCESS;
                } else {
                    JSONObject jsonToMap = JSONObject.parseObject(custTaskQueue.getArgs());
                    Integer withdrawId = (Integer) jsonToMap.get("id");
                    String adminNickName = String.valueOf(jsonToMap.get("admin_id"));

                    CashBackRes res = null;
                    try {
                        res = HeavyUtil.runWithLock(HeavyKeyEnum.WITHDRAWAL_REQUEST.getCode() + withdrawId,
                                () -> withdrawService.doWithdraw(withdrawId, adminNickName, true));
                        if (res == null) {
                            log.info("=batchWithdrawalJob_l=批量提现一条,出现提现被占用;提现id:{}", withdrawId);
                            custTaskQueue.setStatus(CustTaskQueueStatusEnum.IS_NOT_RUNN.getCode());
                        } else {
                            log.info("=batchWithdrawalJob_l=批量提现一条;提现id:{}", withdrawId);
                            custTaskQueue.setStatus(CustTaskQueueStatusEnum.EXECUTE_SUCCESSFUL.getCode());
                        }

                        iCustTaskQueueService.updateById(custTaskQueue);
                    } catch (Exception e) {
                        custTaskQueue.setStatus(CustTaskQueueStatusEnum.ON_FAILURE.getCode());
                        iCustTaskQueueService.updateById(custTaskQueue);
                        MsgSendUtil.sendLarkMsg("=batchWithdrawalJob_l=定时任务处理后台线上提现报错日志;withdrawId:{};{}", withdrawId, e);
                        log.error("=batchWithdrawalJob_l=定时任务处理后台线上提现报错日志;withdrawId:{};{}", withdrawId, e);
                    }
                }

            }
        } catch (Exception e) {
            log.error("=batchWithdrawalJob_l=执行报错", e);
            return ReturnT.FAIL;
        }
        log.info("=batchWithdrawalJob_l=执行结束");
        return ReturnT.SUCCESS;
    }

}
